package com.xneure.code;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class NioClient extends NioSocket{
	public void connect(String serverIp,int port) throws IOException{
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false);
		channel.connect(new InetSocketAddress(serverIp,port));
		channel.register(getSelector(),SelectionKey.OP_CONNECT);
		listen();
	}

	public static void main(String[] args) throws IOException{
		new NioClient().connect("127.0.0.1",9981);
	}

	@Override
	void event(SelectionKey key) throws IOException{
		if(key.isConnectable()){
			SocketChannel channel = (SocketChannel)key.channel();
			if(channel.isConnectionPending()){
				channel.finishConnect();
			}
			listenHandler(getSelector(),channel);
			sendObject("链接成功");
		}
	}

	@Override
	void receiveMsg(byte[] data,int length){
		System.err.println(new String(data,0,length));
	}
}
